﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using WpfApp1.Enum;
using WpfApp1.Model;

namespace WpfApp1.ViewModel
{
    class TrainViewModel
    {
        private ObservableCollection<TrainModel> trains = new ObservableCollection<TrainModel>();

        public TrainViewModel()
        {
            string sql_table = "create table if not exists train (id integer primary key autoincrement,subject int(2),kind int(2),area nvarchar,addr nvarchar,chain_shop nvarchar,start_time nvarchar," +
                "end_time nvarchar,type int(2),require nvarchar,ppt_path nvarchar,len int,summary nvarchar,feedback nvarchar,effect nvarchar,parent_id int)";
            SQLiteCommand command = new SQLiteCommand(sql_table, MainWindow.connecttion);
            command.ExecuteNonQuery();
            SetModel();
        }

        public ObservableCollection<TrainModel> Trains { get => trains; set => trains = value; }

        private void SetModel()
        {
            string sql_all = "select id,parent_id,subject,kind,type,area,chain_shop,start_time,end_time from train";
            SQLiteCommand command = new SQLiteCommand(sql_all, MainWindow.connecttion);
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                long subject = Convert.ToInt64(reader["subject"]);
                string kind = reader["kind"].ToString();
                TrainType type = (TrainType)reader["type"];
                DateTime start = Convert.ToDateTime(reader["start_time"].ToString());
                DateTime end = Convert.ToDateTime(reader["end_time"].ToString());

                string[] kinds = kind.Split(",".ToCharArray());
                List<ProductKind> kindsList = new List<ProductKind>();
                foreach (string kindStr in kinds)
                {
                    if (kindStr == "")
                    {
                        kindsList.Add((ProductKind)0);
                    }
                    else
                    {
                        kindsList.Add((ProductKind)System.Enum.Parse(typeof(ProductKind), kindStr));
                    }
                }

                trains.Add(new TrainModel()
                {
                    Id = Convert.ToInt64(reader["id"]),
                    ParentId = Convert.ToInt64(reader["parent_id"]),
                    Subject = (TrainSubject)subject,
                    Kind = kind,
                    Area = reader["area"].ToString(),
                    ChainShop = reader["chain_shop"].ToString(),
                    StartTime = start,
                    EndTime = end,
                    Type = type,
                    Kinds = kindsList
                });
            }
        }
    }
}
